# -*- coding:utf-8 -*-
import re
import time
from django.core.exceptions import ObjectDoesNotExist

from store.models import WXAutoReply


WX_RE_PATTERN = {
    'ToUserName': r'<ToUserName><!\[CDATA\[(?P<ToUserName>.*)\]\]></ToUserName>',
    'FromUserName': r'<FromUserName><!\[CDATA\[(?P<FromUserName>.*)\]\]></FromUserName>',
    'MsgType': r'<MsgType><!\[CDATA\[(?P<MsgType>.*)\]\]></MsgType>',
    'Content': r'<Content><!\[CDATA\[(?P<Content>.*)\]\]></Content>',
    'PicUrl': r'<PicUrl><!\[CDATA\[(?P<PicUrl>.*)\]\]></PicUrl>',
    'Event': r'<Event><!\[CDATA\[(?P<Event>.*)\]\]></Event>',
    'CreateTime': r'<CreateTime>(?P<CreateTime>[0-9]+)</CreateTime>',
    'MsgId': r'<MsgId>(?P<MsgId>[0-9]+)</MsgId>',
    'EventKey': r'<EventKey><!\[CDATA\[(?P<EventKey>.*)\]\]></EventKey>'
}
WX_WELCOME_MOTTO = u'欢迎关注「镇雄花园宝宝」。你过来，我有个恋爱跟你谈一下！'
WX_TEXT_REPLY_TPL = """
    <xml>
        <ToUserName><![CDATA[%(ToUserName)s]]></ToUserName>
        <FromUserName><![CDATA[%(FromUserName)s]]></FromUserName>
        <CreateTime>%(CreateTime)d</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[%(Content)s]]></Content>
    </xml>
"""

WX_NEWS_REPLY_TPL = """
    <xml>
        <ToUserName><![CDATA[%(ToUserName)s]]></ToUserName>
        <FromUserName><![CDATA[%(FromUserName)s]]></FromUserName>
        <CreateTime>%(CreateTime)d</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <ArticleCount>1</ArticleCount>
        <Articles>
            <item>
                <Title><![CDATA[%(Title)s]]></Title>
                <Description><![CDATA[%(Description)s]]></Description>
                <PicUrl><![CDATA[%(PicUrl)s]]></PicUrl>
                <Url><![CDATA[%(Url)s]]></Url>
            </item>
        </Articles>
    </xml>
"""
WX_CLICK_REPLY_TPL_DICT = {
    'FAKE1': {
        'Title': u'第8季中国校花大赛开始啦',
        'Description': u'国内规模最大的校花大赛火热进行中,下一个中国校花会是谁?',
        'PicUrl': 'http://7xlzeh.com2.z0.glb.qiniucdn.com/weixinface.jpg',
        'Url': 'http://mp.weixin.qq.com/s?__biz=MzI1NTAwODMwMw==&mid=402688170&idx=1&sn=b0e4cd8479552cb265dc1c75cbfaa5e7#rd'
    },
    'FAKE2': {
        'Title': u'第8季中国校花大赛开始啦',
        'Description': u'国内规模最大的校花大赛火热进行中,下一个中国校花会是谁?',
        'PicUrl': 'http://7xlzeh.com2.z0.glb.qiniucdn.com/weixinface.jpg',
        'Url': 'http://mp.weixin.qq.com/s?__biz=MzI1NTAwODMwMw==&mid=402688170&idx=1&sn=b0e4cd8479552cb265dc1c75cbfaa5e7#rd'
    }
}


def content_to_dict(content):
    rtv_dict = {}
    for item in WX_RE_PATTERN:
        matches = re.search(WX_RE_PATTERN[item], content, re.S)
        if matches:
            rtv_dict[item] = matches.group(item)
    return rtv_dict


def deal_subscribe_event(message):
    if message['MsgType'] == 'event':
        if message['Event'] == 'subscribe':
            return WX_TEXT_REPLY_TPL % {
                'FromUserName': message['ToUserName'],
                'ToUserName': message['FromUserName'],
                'CreateTime': int(time.time()),
                'Content': WX_WELCOME_MOTTO
            }
        elif message['Event'] == 'unsubscribe':
            return 'unsubscribe'


def deal_click_action(message):
    if not(message['MsgType'] == 'event' and message['Event'] == 'CLICK'):
        return ''
    content = {
        'FromUserName': message['ToUserName'],
        'ToUserName': message['FromUserName'],
        'CreateTime': int(time.time()),
    }
    content.update(WX_CLICK_REPLY_TPL_DICT[message['EventKey']])
    return WX_NEWS_REPLY_TPL % content


def deal_text_input(message):
    if message['MsgType'] != 'text':
        return ''
    try:
        item = WXAutoReply.objects.get(keyword=message['Content'])
        item.request_num += 1
        item.save()
        content = {
            'FromUserName': message['ToUserName'],
            'ToUserName': message['FromUserName'],
            'CreateTime': int(time.time()),
            'Content': item.reply
        }
        return WX_TEXT_REPLY_TPL % content
    except ObjectDoesNotExist:
        return ''
